﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Flow;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.FlowManager;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Extend.ModelExtend.FlowExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;

namespace SJ.Platform.Api.Controllers.FlowManager
{
    /// <summary>
    /// 流程操作类
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Flow")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class FlowManagerController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly ICurrentUser _currentUser;
        private readonly Flow_MainHandle flow_mainHandle;
        private readonly Flow_NodeHandle flow_nodeHandle;
        private readonly Flow_Node_ApproveUserHandle flow_Node_ApproveUserHandle;
        private readonly Flow_TypeHandle flow_TypeHandle;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public FlowManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            _currentUser = currentUser;
            flow_mainHandle = new Flow_MainHandle(dbContext);
            flow_nodeHandle = new Flow_NodeHandle(dbContext);
            flow_Node_ApproveUserHandle = new Flow_Node_ApproveUserHandle(dbContext);
            flow_TypeHandle = new Flow_TypeHandle(dbContext);
        }

        /// <summary>
        /// 新增流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateFlowAsync")]
        public async Task<IActionResult> CreateFlowAsync([FromBody] FlowMain model)
        {
            var Flow = new FlowMain
            {
                Id = Guid.NewGuid().ToString(),
                FlowName = model.FlowName,
                FlowTypeId = model.FlowTypeId,
                FlowTypeName = model.FlowTypeName,
                IsUsed = model.IsUsed,
                AddTime = DateTime.Now,
                AddUserId = _currentUser.UserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };

            try
            {
                bool result = await flow_mainHandle.CreateAsync(Flow);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "流程添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "流程添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateFlowAsync")]
        public async Task<IActionResult> UpdateFlowAsync([FromBody] FlowMain model)
        {
            var Flow = new FlowMain
            {
                Id = model.Id,
                FlowName = model.FlowName,
                FlowTypeId = model.FlowTypeId,
                FlowTypeName = model.FlowTypeName,
                IsUsed = model.IsUsed,
                AddTime = model.AddTime,
                AddUserId = model.AddUserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };

            try
            {
                bool result = await flow_mainHandle.UpdateAsync(Flow);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "流程修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "流程修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除流程
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByFlowIdAsync/{flowId}")]
        public async Task<IActionResult> DeleteByFlowIdAsync(string flowId)
        {
            try
            {
                bool result = await flow_mainHandle.DeleteByIdAsync(flowId);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除流程" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除流程失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 获取所有流程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllFlowAsync")]
        public async Task<IActionResult> GetAllFlowAsync([FromBody] ApiPageQueryRequest<FlowMain> request)
        {
            try
            {
                var result = await flow_mainHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<FlowMain>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<FlowMain>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.flows)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<FlowMain>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<FlowMain> { }));
            }
        }

        /// <summary>
        /// 获取流程详情
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        [HttpGet("GeFlowDetailAsync/{flowId}")]
        public async Task<IActionResult> GetFlowDetailAsync(string flowId)
        {
            try
            {
                var result = await flow_mainHandle.GetEntityByIdAsync(flowId);

                return Ok(ApiNormalResponse<FlowMain>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<FlowMain>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, null));
            }
        }

        /// <summary>
        /// 获取所有流程类型
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllFlowTypeAsync")]
        public async Task<IActionResult> GetAllFlowTypeAsync([FromBody] ApiPageQueryRequest<FlowType> request)
        {
            try
            {
                var result = await flow_TypeHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<FlowType>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<FlowType>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.flows)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<FlowType>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<FlowType> { }));
            }
        }

        /// <summary>
        /// 新增流程类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateFlowTypeAsync")]
        public async Task<IActionResult> CreateFlowTypeAsync([FromBody] FlowType model)
        {
            var flowType = new FlowType
            {
                Id = Guid.NewGuid().ToString(),
                Pid = model.Pid,
                TypeName = model.TypeName,
                PName = model.PName,
                AddTime = DateTime.Now,
                AddUserId = _currentUser.UserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };

            try
            {
                bool result = await flow_TypeHandle.CreateAsync(flowType);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "流程类型添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "流程类型添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改流程类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateFlowTypeAsync")]
        public async Task<IActionResult> UpdateFlowTypeAsync([FromBody] FlowType model)
        {
            var flowType = new FlowType
            {
                Id = model.Id,
                Pid = model.Pid,
                TypeName = model.TypeName,
                PName = model.PName,
                AddTime = model.AddTime,
                AddUserId = model.AddUserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };

            try
            {
                bool result = await flow_TypeHandle.UpdateAsync(flowType);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "流程类型修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "流程类型修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除流程类型
        /// </summary>
        /// <param name="flowTypeId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByFlowTypeIdAsync/{flowTypeId}")]
        public async Task<IActionResult> DeleteByFlowTypeIdAsync(string flowTypeId)
        {
            try
            {
                bool result = await flow_TypeHandle.DeleteByIdAsync(flowTypeId);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除流程类型" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除流程类型失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 获取流程类型树
        /// </summary>
        /// <returns></returns>
        [HttpGet("GeFlowTypeTreeAsync")]
        public async Task<IActionResult> GeFlowTypeTreeAsync()
        {
            try
            {
                var result = await flow_TypeHandle.GetFlowTypeTreeAsync();

                return Ok(ApiNormalResponse<List<FlowTypeExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<FlowTypeExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<FlowTypeExtend>() { }));
            }
        }

        /// <summary>
        /// 获取所有项目流程类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetProjectFlowTypeAsync")]
        public async Task<IActionResult> GetProjectFlowTypeAsync()
        {
            try
            {
                var result = await flow_TypeHandle.GetProjectFlowTypeAsync();

                return Ok(ApiNormalResponse<List<FlowType>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<FlowType>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<FlowType>() { }));
            }
        }

        /// <summary>
        /// 新增流程节点
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateFlowNodeAsync")]
        public async Task<IActionResult> CreateFlowNodeAsync([FromBody] FlowNodeExtend model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    var flowNode = new FlowNode
                    {
                        Id = Guid.NewGuid().ToString(),
                        Fid = model.Fid,
                        NodeName = model.NodeName,
                        ApproveRoleId = model.ApproveRoleId,
                        ApproveRoleName = model.ApproveRoleName,
                        ApproveType = model.ApproveType,
                        PassCondition = model.PassCondition,
                        PrevNodeId = model.PrevNodeId,
                        PrevNodeName = model.PrevNodeName,
                        Sort = model.Sort,
                        AddTime = DateTime.Now,
                        AddUserId = _currentUser.UserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };

                    bool actionResult = await flow_nodeHandle.CreateAsync(flowNode);
                    //专人审批的审批人
                    if (actionResult && model.ApproveType == 1 && model.flowNodeApproveUsers != null && model.flowNodeApproveUsers.Count > 0)
                    {
                        List<FlowNodeApproveUser> list = new List<FlowNodeApproveUser>();
                        foreach (FlowNodeApproveUser au in model.flowNodeApproveUsers)
                        {
                            list.Add(new FlowNodeApproveUser { NodeId = flowNode.Id, ApproveUserId = au.ApproveUserId, ApproveUserName = au.ApproveUserName });
                        }

                        actionResult = await flow_Node_ApproveUserHandle.CreateAsync(list);
                    }

                    return actionResult;
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "流程类型添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "流程类型添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改流程节点
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateFlowNodeAsync")]
        public async Task<IActionResult> UpdateFlowNodeAsync([FromBody] FlowNodeExtend model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    var flowNode = new FlowNode
                    {
                        Id = model.Id,
                        Fid = model.Fid,
                        NodeName = model.NodeName,
                        ApproveRoleId = model.ApproveRoleId,
                        ApproveRoleName = model.ApproveRoleName,
                        ApproveType = model.ApproveType,
                        PassCondition = model.PassCondition,
                        PrevNodeId = model.PrevNodeId,
                        PrevNodeName = model.PrevNodeName,
                        Sort = model.Sort,
                        AddTime = model.AddTime,
                        AddUserId = _currentUser.UserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };

                    bool actionResult = await flow_nodeHandle.UpdateAsync(flowNode);
                    //专人审批的审批人
                    if (actionResult && model.ApproveType == 1)
                    {
                        //先删除
                        actionResult = await flow_Node_ApproveUserHandle.DeleteByNodeIdAsync(model.Id);

                        //再添加
                        if (actionResult && model.flowNodeApproveUsers != null && model.flowNodeApproveUsers.Count > 0)
                        {
                            List<FlowNodeApproveUser> list = new List<FlowNodeApproveUser>();
                            foreach (FlowNodeApproveUser au in model.flowNodeApproveUsers)
                            {
                                list.Add(new FlowNodeApproveUser { NodeId = flowNode.Id, ApproveUserId = au.ApproveUserId, ApproveUserName = au.ApproveUserName });
                            }

                            actionResult = await flow_Node_ApproveUserHandle.CreateAsync(list);
                        }
                    }

                    return actionResult;
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "流程类型修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "流程类型修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除流程节点
        /// </summary>
        /// <param name="flowNodeId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByFlowNodeIdAsync/{flowNodeId}")]
        public async Task<IActionResult> DeleteByFlowNodeIdAsync(string flowNodeId)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    return await flow_nodeHandle.DeleteByIdAsync(flowNodeId) && await flow_Node_ApproveUserHandle.DeleteByNodeIdAsync(flowNodeId);
                });
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除流程类型" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除流程类型失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 获取流程节点
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        [HttpGet("GeFlowNodeByFlowIdAsync/{flowId}")]
        public async Task<IActionResult> GeFlowNodeByFlowIdAsync(string flowId)
        {
            try
            {
                var result = await flow_nodeHandle.GeFlowNodeByFlowIdAsync(flowId);

                return Ok(ApiNormalResponse<List<FlowNode>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<FlowNode>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<FlowNode>() { }));
            }
        }

        /// <summary>
        /// 获取流程启动节点
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        [HttpGet("GeFlowStartNodeByFlowIdAsync/{flowId}")]
        public async Task<IActionResult> GeFlowStartNodeByFlowIdAsync(string flowId)
        {
            try
            {
                var result = await flow_nodeHandle.GeFlowStartNodeByFlowIdAsync(flowId);

                return Ok(ApiNormalResponse<FlowNode>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<FlowNode>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, null));
            }
        }

        /// <summary>
        /// 获取专人审批节点对应的审批人
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        [HttpGet("GetApproveUserByNodeIdAsync/{nodeId}")]
        public async Task<IActionResult> GetApproveUserByNodeIdAsync(string nodeId)
        {
            try
            {
                var result = await flow_Node_ApproveUserHandle.GetEntityListByNodeIdAsync(nodeId);

                return Ok(ApiNormalResponse<List<FlowNodeApproveUser>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<FlowNodeApproveUser>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<FlowNodeApproveUser>() { }));
            }
        }

    }
}
